package com.haier.npt.sso.utils;


import javax.servlet.http.HttpServletRequest;

import org.springframework.util.Base64Utils;

import com.haier.npt.exception.BizBaseException;
import com.haier.npt.exception.ExceptionCode;
import com.haier.npt.security.domain.SysApp;


public class AuthorizationUtil {

	/**
	 * 从参数或者cookie 中获取token
	 * 
	 * @param request
	 * @return
	 */
	public static String getRequestAccessToken(HttpServletRequest request) {
		String access_token = request.getParameter("access_token");

		if (access_token == null) {
			String authorization = request.getHeader("Authorization");
			if (authorization == null) {
				return null;
			}
			authorization = authorization.toLowerCase();
			if (authorization.startsWith("bearer ")) {
				access_token = authorization.substring("bearer ".length());
			}

		}
		return access_token;
	}


	public static SysApp decodeCredential(String base64Str) {
		if(base64Str.startsWith("basic")){
			base64Str = base64Str.replace("basic", "").trim();
		}
		if(base64Str.startsWith("Basic")){
			base64Str = base64Str.replace("Basic", "").trim();
		}
		/**
		 * base64解码
		 */
		String clientCredential = new String(Base64Utils.decodeFromString(base64Str));

		// 验证是否包含：
		if (clientCredential != null && clientCredential.contains(":")) {
			String[] array = clientCredential.split(":"); // 数据长度为2
			if (array.length == 2) {
				SysApp sysAppInfo = new SysApp();
				sysAppInfo.setApp_key(array[0]);
				sysAppInfo.setApp_secret(array[1]);
				return sysAppInfo;
			}
		}
		throw new BizBaseException(ExceptionCode.SYS_APP_ERROR); // 不合法
	}

}
